
package com.mengmeizi;

import com.mengmeizi.adapter.ManagerImagesAdapter;
import com.mengmeizi.bean.ImageBean;
import com.mengmeizi.bean.ViewHolder;
import com.mengmeizi.db.DBHelper;
import com.mengmeizi.db.WallpaperDBBean;
import com.mengmeizi.services.ChangeWallpaperService;
import com.mengmeizi.util.Const;
import com.mengmeizi.util.ImageManager;
import com.mengmeizi.util.Tools;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;

public class ActManager extends Activity implements OnClickListener, Callback, OnItemClickListener {

    private SoftApplication application;

    private GridView gridView;

    private ManagerImagesAdapter msgAdapter;

    private TextView txvDelImage;

    private ImageView imvTitle;

    private Button btnCancel, btnDelete, btnEdit, btnMore;

    /** 是否点击了编辑按钮 */
    private boolean isEdit;

    private ArrayList<String> localImagesPath;

    private ArrayList<String> selImagesPath;

    private DBHelper helper;

    private Handler handler;

    private boolean isShowing;

    private ImageView imvDefault;

    /** 编辑按钮是否可点击 */
    private Boolean isEditEnable = false;

    private SharedPreferences preSetting;

    private String selectedImage;

    private boolean isFinished;

    private boolean backDetail = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_manager);

        application = (SoftApplication) getApplication();
        application.addActivity(this);

        handler = new Handler(this);

        helper = new DBHelper(this, WallpaperDBBean.TABLE);

        initManagerView();
    }

    private void initManagerView() {
        imvTitle = (ImageView) findViewById(R.id.imvTitle);
        imvTitle.setOnClickListener(this);

        txvDelImage = (TextView) findViewById(R.id.txvDelImage);

        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnMore = (Button) findViewById(R.id.btnMore);
        btnEdit.setOnClickListener(this);
        btnMore.setOnClickListener(this);

        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnCancel.setOnClickListener(this);
        btnDelete.setOnClickListener(this);

        imvDefault = (ImageView) findViewById(R.id.imvDefault);

        isEdit = false;
        setTitleLayout();

        if (localImagesPath == null) {
            localImagesPath = new ArrayList<String>();
        }

        gridView = (GridView) findViewById(R.id.gvImages);
        gridView.setOnItemClickListener(this);
        msgAdapter = new ManagerImagesAdapter(this, localImagesPath);
        gridView.setAdapter(msgAdapter);

        preSetting = getSharedPreferences(Const.SHARED_PREFERENCES_MESSAGE, Context.MODE_PRIVATE);
        if (preSetting.getBoolean(Const.SHP_MANAGER, true)) {
            imvDefault.setVisibility(View.VISIBLE);
            imvDefault.setImageResource(R.drawable.pic_manager_default);
            imvDefault.setOnClickListener(this);
            imvDefault.setScaleType(ScaleType.FIT_XY);
        } else {
            imvDefault.setScaleType(ScaleType.FIT_CENTER);
            // imageFileScan();
        }
    }

    /** 获取本地存储的图片 */
    private void imageFileScan() {
        new Thread() {

            @Override
            public void run() {
                super.run();
                // 显示加载对话框
                handler.sendEmptyMessage(Const.DIALOG_SHOW);
                if (localImagesPath != null) {
                    localImagesPath.clear();
                }
                File file = new File(Const.FILENAME_DOWNLOAD);
                if (!file.exists()) { // 不存在download文件夹
                    file.mkdirs();
                    handler.sendEmptyMessage(Const.MANAGER_NO_SAVEIMAGES);
                } else {
                    File[] fileImages = file.listFiles();
                    String tmpString = null;
                    WallpaperDBBean tmpBean = null;
                    if (fileImages.length > 0) {
                        helper.openWritableDatabase();
                        helper.clearAllRecord();
                        isEditEnable = true;
                        for (int i = 0; i < fileImages.length; i++) {
                            if (fileImages[i].isFile()) {
                                tmpString = fileImages[i].getAbsolutePath();
                                localImagesPath.add(tmpString);
                                // 存入数据库
                                tmpBean = new WallpaperDBBean();
                                tmpBean.index = i;
                                tmpBean.imageUrl = "";
                                tmpBean.localPath = tmpString;
                                helper.insertItem(tmpBean.conver2ContentValues());
                            }
                        }
                        helper.close();
                        handler.sendEmptyMessage(Const.REFRESH_IMG);
                    } else { // download文件夹为空
                        handler.sendEmptyMessage(Const.MANAGER_NO_SAVEIMAGES);
                    }
                }
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
            }

        }.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isEdit) {
                isEdit = false;
                setTitleLayout();
            } else {
                this.finish();
            }
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        if (v instanceof ImageView) {
            if (v == imvTitle) {
                this.finish();
            } else if (v == imvDefault) {

                Editor editor = preSetting.edit();
                editor.putBoolean(Const.SHP_MANAGER, false);
                editor.commit();

                imvDefault.setClickable(false);
                imvDefault.setVisibility(View.GONE);
                // imageFileScan();
            } else {
                // ImageBean imageBean = (ImageBean) v.getTag();
                // if (imageBean != null) {
                // if (isEdit) {
                // imageBean.isChecked = !imageBean.isChecked;
                // if (imageBean.isChecked) {
                // imageBean.selImage.setVisibility(View.VISIBLE);
                // selImagesPath.add(imageBean.urlString);
                // } else {
                // imageBean.selImage.setVisibility(View.GONE);
                // // 再按一次取消删除选择
                // selImagesPath.remove(selImagesPath.indexOf(imageBean.urlString));
                // }
                // } else {
                // backDetail = true;
                // // 进入详细页
                // Intent intent = new Intent(this, ActImageDetail.class);
                // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // Bundle bundle = new Bundle();
                // selectedImage = imageBean.urlString;
                // bundle.putString(Const.BUNDLE_IMAGEURL, selectedImage);
                // bundle.putBoolean(Const.IS_MANAGER, true);
                // intent.putExtras(bundle);
                // // Tools.switchActivity(this, ActImageDetail.class,
                // // bundle);
                // // startActivityForResult(intent,
                // // Const.ACT$MANAGER_ACTION);
                //
                // startActivity(intent);
                // }
                // }
            }
        } else if (v instanceof Button) {// Button extends TextView
            if (v == btnCancel) {
                this.isEdit = false;
                setTitleLayout();
                // 清空选择
                if (selImagesPath != null) {
                    selImagesPath.clear();
                }
                handler.sendEmptyMessage(Const.REFRESH_IMG);
            } else if (v == btnDelete) {
                // this.isEdit = false;
                // setTitleLayout();
                if (selImagesPath.size() > 0) {
                    delSelImages();
                } else {
                    Tools.showShortToast(ActManager.this, getString(R.string.chooseDelImage));
                }
            } else if (v == btnEdit) {
                if (isEditEnable) {
                    if (selImagesPath == null) {
                        selImagesPath = new ArrayList<String>();
                    }
                    this.isEdit = true;
                    setTitleLayout();
                }
            } else if (v == btnMore) {
                Tools.switchActivity(this, ActMore.class, null);
                // this.finish();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Const.ACT$MANAGER_ACTION:
                if (resultCode == Const.ACT_DELETE) {
                    String deleString = data.getStringExtra(Const.RESULT_DATA);
                    localImagesPath.remove(localImagesPath.indexOf(deleString));
                    // 刷新
                    Message msg = handler.obtainMessage();
                    msg.what = Const.REFRESH_IMG;
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                    // 显示提示
                    msg = handler.obtainMessage();
                    msg.what = Const.SHOW_TOAST;
                    msg.obj = getString(R.string.imageDelSuccess);
                    handler.sendMessage(msg);
                }
                break;

            default:
                break;
        }
    }

    /** 删除所选的图片 */
    private void delSelImages() {
        new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                super.run();
                handler.sendEmptyMessage(Const.DIALOG_SHOW);
                helper.openWritableDatabase();
                int delCount = selImagesPath.size();
                String delPath = null;
                for (int i = 0; i < delCount; i++) {
                    delPath = selImagesPath.get(i);

                    File tmpFile = new File(delPath);
                    if (tmpFile.exists()) { // 如果文件存在，删除文件
                        tmpFile.delete();
                        helper.deleteItem(WallpaperDBBean.sql$delete(delPath));
                    }
                    // 移除本地地址字符串
                    localImagesPath.remove(localImagesPath.indexOf(delPath));
                }
                selImagesPath.clear();
                helper.close();
                // 刷新后，gridview自动把不存在于数据中的图片清除
                Message msgDel = handler.obtainMessage();
                msgDel.arg1 = 1;
                msgDel.what = Const.REFRESH_IMG;
                handler.sendMessage(msgDel);
                // handler.sendEmptyMessage(Const.REFRESH_IMG); //
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                // 删除提示
                Message msg = handler.obtainMessage();
                msg.what = Const.SHOW_TOAST;
                msg.obj = getString(R.string.imageDelSuccess);
                handler.sendMessage(msg);
            }

        }.start();
    }

    /***
     * @param isEdit 是否点击了编辑
     */
    private void setTitleLayout() {
        if (isEdit) {
            imvTitle.setVisibility(View.GONE);
            btnEdit.setVisibility(View.GONE);
            btnMore.setVisibility(View.GONE);

            txvDelImage.setVisibility(View.VISIBLE);
            btnCancel.setVisibility(View.VISIBLE);
            btnDelete.setVisibility(View.VISIBLE);
        } else {
            txvDelImage.setVisibility(View.GONE);
            btnCancel.setVisibility(View.GONE);
            btnDelete.setVisibility(View.GONE);

            imvTitle.setVisibility(View.VISIBLE);
            btnEdit.setVisibility(View.VISIBLE);
            btnMore.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Const.REFRESH_IMG:
                msgAdapter.notifyDataSetChanged();
                if (localImagesPath.size() == 0) { // 没有图片了
                    handler.sendEmptyMessage(Const.MANAGER_NO_SAVEIMAGES);
                    this.isEdit = false;
                    setTitleLayout();
                }
                if (msg.arg1 == 1) { // 删除后刷新
                    if (localImagesPath.size() < 2) {
                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
                        if (preferences.getBoolean(Const.SHARED_WALLPAPER_SWITCHER, true)) {
                            // 发送提示
                            msg = handler.obtainMessage();
                            msg.what = Const.SHOW_TOAST;
                            msg.obj = getString(R.string.closeAutoSwitch);
                            handler.sendMessage(msg);
                            // 改变属性
                            Editor editor = preferences.edit();
                            editor.putBoolean(Const.SHARED_WALLPAPER_SWITCHER, false);
                            editor.commit();
                            // 取消闹钟
                            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                            Intent intent = new Intent(this, ChangeWallpaperService.class);
                            PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
                            alarmManager.cancel(pendingIntent);
                        }
                    }
                }
                break;
            case Const.DIALOG_SHOW:
                showDialog(Const.DIALOG_ID);
                isShowing = true;
                break;
            case Const.DIALOG_DISMISS:
                if (isShowing) {
                    isShowing = false;
                    dismissDialog(Const.DIALOG_ID);
                }
                break;
            case Const.MANAGER_NO_SAVEIMAGES:
                gridView.setVisibility(View.GONE);
                // 显示默认图片
                isEditEnable = false;
                LayoutParams laParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
                laParams.addRule(RelativeLayout.BELOW, R.id.title_layout);
                imvDefault.setScaleType(ScaleType.FIT_CENTER);
                imvDefault.setImageResource(R.drawable.img_manager_default);
                imvDefault.setVisibility(View.VISIBLE);
                break;
            case Const.SHOW_TOAST:
                Tools.showShortToast(this, (String) msg.obj);
            default:
                break;
        }
        return false;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        ProgressDialog dialog = new ProgressDialog(this);
        // dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.refresh_round));
        dialog.setMessage(getString(R.string.loading));
        dialog.setIndeterminate(false);
        return dialog;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isFinished = true;
        isShowing = false;
        int childCount = localImagesPath.size();
        try {
            Bitmap tmpBitmap = null;
            for (int i = 0; i < childCount; i++) {
                tmpBitmap = gridView.getChildAt(i).findViewById(R.id.imvImage).getDrawingCache();
                if (tmpBitmap != null) {
                    tmpBitmap.recycle();
                    ImageManager.getManger().removeBitmap(tmpBitmap, localImagesPath.get(i));
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    protected void onNewIntent(Intent intent) { // ActManager设置了singleInstance，可以通过这个方法获取重新启动ActManager的intent数据
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        // 每次进入manager都会执行这里，如果不是删除了图片，都不需要重新扫描
        backDetail = intent.getBooleanExtra("delete", true);
    }

    public void onResume() {
        super.onResume();
        if (!isFinished && !backDetail) {
            backDetail = false;
            imageFileScan();
        }
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        ImageBean imageBean = (ImageBean) viewHolder.imvImage.getTag();
        if (imageBean != null) {
            if (isEdit) {
                imageBean.isChecked = !imageBean.isChecked;
                if (imageBean.isChecked) {
                    imageBean.selImage.setVisibility(View.VISIBLE);
                    selImagesPath.add(imageBean.urlString);
                } else {
                    imageBean.selImage.setVisibility(View.GONE);
                    // 再按一次取消删除选择
                    selImagesPath.remove(selImagesPath.indexOf(imageBean.urlString));
                }
            } else {
                backDetail = true;
                // 进入详细页
                Intent intent = new Intent(this, ActImageDetail.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Bundle bundle = new Bundle();
                selectedImage = imageBean.urlString;
                bundle.putString(Const.BUNDLE_IMAGEURL, selectedImage);
                bundle.putBoolean(Const.IS_MANAGER, true);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }
    }
}
